package com.xgf.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.xgf.util.base.BusException;
import com.xgf.util.base.RetCode;

import sun.misc.BASE64Decoder;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

/**
 * Created by Administrator on 2017/4/18.
 */
public class Base64Util {
    private static Log logger = LogFactory.getLog(Base64Util.class);
    public static boolean generateImage(String imgStr, String path) {
        if (imgStr == null)
            return false;

        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // 解密
            byte[] b = decoder.decodeBuffer(imgStr);
            //判断base64数据是否为JPG,jpg,BMP,bmp,GIF,gif,WBMP,wbmp,PNG,png,JPEG,jpeg后缀的图片
//            String names[] = ImageIO.getReaderFormatNames();
            BufferedImage bufImg = ImageIO.read(new ByteArrayInputStream(b));
//            if(bufImg)
//            {
//
//            }
            // 处理数据
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            OutputStream out = new FileOutputStream(path);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * Created by leno on 2017/04/24
     * 判断base64串是不是图片文件
     * @param base64Str
     * @return
     */
    public static boolean isImageFromBase64(String base64Str){
        boolean flag = false;
        try {
            BufferedImage bufImg = ImageIO.read(new ByteArrayInputStream(new BASE64Decoder().decodeBuffer(base64Str)));
            if (null == bufImg) {
                return flag;
            }
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(e.getStackTrace());
            throw new BusException(RetCode.RET_FAILED,"系统异常！");
        }
        return flag;
    }

    /**
     *  Created by leno on 2016/12/15
     *  传一个预期路径，过程中的文件夹允许不存在，file.getParentFile()会逐层向上查询，直至查到有父文件夹的根目录，然后利用递归函数创建子文件夹
     * @param file
     */
    public static String mkDir(File file) {
        //定义一个变量用来接收文件夹路径
        String path = file.getPath();
        if (file.getParentFile().exists()) {
            //创建文件夹
            file.mkdir();
        } else {
            //file.getParentFile()查询当前文件夹是否有父文件夹
            mkDir(file.getParentFile());
            file.mkdir();
            path = file.getPath();
        }
        return path;
    }
}
